//
// Created by 32827 on 2024/2/6.
//
#include "yzl_clock.h"
YZL_CLOCK yzl_system_clock;
YZL_CLOCK *yzl_clock_get(){
    return &yzl_system_clock;
}
uint32_t system_min;
//TODO: 解耦，是更加兼容,主要是对参数
void yzl_clock_init(void){

    yzl_system_clock.min=&system_min;
    yzl_system_clock.us=&TIMER_CNT(YZL_TIMER);

    yzf_tim_open_clock(YZL_TIMER);
    yzf_tim_clock_div(YZL_TIMER,0);
    yzf_tim_set_prescaler(YZL_TIMER,120);
    yzf_tim_set_period(YZL_TIMER,60000000);
    yzf_tim_int_UP(YZL_TIMER,YZF_TRUE);

    yzf_tim_enable(YZL_TIMER);

    yzf_nvic_irq_enable(TIMER1_IRQn);
    yzf_nvic_irq_set_priority(TIMER1_IRQn,0b00000000);
}
void YZL_CLOCK_IRQ_NAME(){
    if(yzf_tim_flag_upie(YZL_TIMER)){
        system_min++;
        yzf_tim_flag_clear_upie(YZL_TIMER);
    }
}
void yzl_clock_delay_us(uint32_t us){
    uint32_t start_us=*yzl_system_clock.us;
    uint32_t end_min=*yzl_system_clock.min;
    uint32_t end_us=*yzl_system_clock.us+us;
    if (start_us+us>=60000000){
        end_us=start_us+us-60000000;
        end_min+=1;
    }
    while (*yzl_system_clock.min<end_min||*yzl_system_clock.us<end_us){
        __asm__("nop"); //阻塞
    }
}
void yzl_clock_delay_ms(uint32_t ms){
    uint32_t min=ms/(60*1000);
    for(uint32_t i=0;i<min;i++){
        yzl_clock_delay_us(60*1000*000);
    }
    yzl_clock_delay_us((ms%(60*1000))*1000);
}
void yzl_clock_delay_s(uint32_t s){
    uint32_t min=s/60;
    for(uint32_t i=0;i<min;i++){
        yzl_clock_delay_us(60*1000*000);
    }
    yzl_clock_delay_us((s%60)*1000*1000);
}